import requests
from flask import current_app
from loguru import logger

class WeChatService:
    """微信服务类"""
    
    def __init__(self):
        self.app_id = current_app.config.get('WECHAT_APP_ID')
        self.app_secret = current_app.config.get('WECHAT_APP_SECRET')
    
    def get_access_token(self, code):
        """获取微信access_token"""
        try:
            url = 'https://api.weixin.qq.com/sns/jscode2session'
            params = {
                'appid': self.app_id,
                'secret': self.app_secret,
                'js_code': code,
                'grant_type': 'authorization_code'
            }
            
            response = requests.get(url, params=params, timeout=10)
            data = response.json()
            
            if 'errcode' in data:
                logger.error(f"微信登录失败: {data}")
                return None
            
            return data
            
        except Exception as e:
            logger.error(f"获取微信access_token失败: {e}")
            return None
    
    def get_user_info(self, code):
        """获取用户信息"""
        try:
            # 获取access_token
            token_data = self.get_access_token(code)
            if not token_data:
                return None
            
            # 返回用户基本信息
            user_info = {
                'openid': token_data.get('openid'),
                'unionid': token_data.get('unionid'),
                'session_key': token_data.get('session_key')
            }
            
            # 注意：微信小程序无法直接获取用户昵称和头像
            # 需要通过用户主动授权获取
            return user_info
            
        except Exception as e:
            logger.error(f"获取用户信息失败: {e}")
            return None
    
    def update_user_info(self, openid, user_info):
        """更新用户信息（通过用户主动授权）"""
        try:
            # 这里可以添加用户信息更新的逻辑
            # 比如保存用户主动授权的昵称、头像等信息
            return True
            
        except Exception as e:
            logger.error(f"更新用户信息失败: {e}")
            return False 